<template>
    <a-divider orientation="left">部署</a-divider>
    <a-form ref="formRef" :model="form" layout="vertical">
        <template v-for="(item, index) in form" :key="item.id">
            <a-card hoverable :title="`部署脚本${index + 1}`" style="width: 100%; margin-bottom: 10px;">
                <template #extra>
                    <MinusCircleOutlined @click="removeItem(item)" />
                </template>
                <a-form-item label="服务器" :name="[index, 'serverIds']" :rules="{
                    required: true,
                    message: '不能为空',
                }">
                    <a-select v-model:value="item.serverIds" mode="multiple" style="width: 100%" :options="options"
                        allowClear>
                    </a-select>
                </a-form-item>

                <a-form-item label="shell脚本" :name="[index, 'command']" :rules="{
                    required: true,
                    message: '不能为空',
                }">
                  <CodeEditor v-model="item.command" type="shell" />
                </a-form-item>
            </a-card>
        </template>
        <a-button type="dashed" block @click="addItem" style="width: 150px;">
            <PlusOutlined />
            添加脚本
        </a-button>
    </a-form>

</template>
<script setup lang="ts">
import * as serverApi from "@/api/serverapi"
import * as projectDeployerApi from '@/api/projectDeployerApi';
import type { ProjectDeployer } from '@/api/projectDeployerApi';
import type { FormInstance } from 'ant-design-vue/lib/form/Form';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { DefaultOptionType } from "ant-design-vue/lib/select";

let data = defineProps<{
    modelValue?: number
}>()

watch(() => data.modelValue, (a) => {
    if (a != undefined && a > 0) {
        form.forEach((item) => {
            item.project_id = a
        })
    }
})

interface DeployerFrom extends ProjectDeployer {
    serverIds?: number[]
}
const options = reactive<DefaultOptionType[]>([])
const form = reactive<DeployerFrom[]>([])
onBeforeMount(() => refresh())

const refresh = (async () => {
    const serverRes = await serverApi.getSelectRows()
    serverRes.data.forEach(item => {
        options.push(item as DefaultOptionType)
    })

    if (data.modelValue == 0) {
        return
    }
    const res = await projectDeployerApi.getProjectId(data.modelValue)
    if (res.code != 0) {
        message.error(res.msg)
        return
    }
    res.data.forEach((item, index) => {
        form.push({
            command: item.command,
            id: item.id,
            project_id: item.project_id,
            serverIds: item.server_ids?.split(",").map(o => Number(o))
        })
    })
})

const removeIds = reactive<number[]>([])
const removeItem = async (item: DeployerFrom) => {
    removeIds.push(item.id ?? 0)

    let index = form.indexOf(item);
    if (index !== -1) {
        form.splice(index, 1);
    }

};
const addItem = () => {
    form.push({
        project_id: data.modelValue
    });
};

const formRef = ref<FormInstance>();
const submit = async () => {
    try {
        await formRef.value?.validateFields()
        form.forEach(item => {
            item.server_ids = item.serverIds?.join(",")
        })
        const res = await projectDeployerApi.save(form)
        const msg = res.filter(o => o.code != 0).map(o => o.msg).join("\n")
        if (msg != "") {
            message.error(msg)
            return false
        }
        const delRes = await projectDeployerApi.remove(removeIds)
        if (delRes.code != 0) {
            message.error(`删除部署脚本失败：${delRes.msg}`)
            return
        }
        return true
    } catch (error) {
        return false
    }
}
defineExpose({ submit })

</script>

